using System;
using Demo.Business;
using MvpFramework;

namespace Demo.Presentation
{
    public class EditPersonPresenter:Presenter<IEditPersonView>
    {
        private readonly IPersonRepository repository;
        internal bool Valid
        {
            get { return IsValid; }
        }

        public EditPersonPresenter(IEditPersonView view, IPersonRepository repository) : base(view)
        {
            this.repository = repository;
            if(View.IsInitialLoad)
            {
                HydrateAllPeople();
            }
            RegisterEvents();
        }
        private void HydrateAllPeople()
        {
            View.AllPeople = repository.GetAll();
        }
        private void RegisterEvents()
        {
            View.PersonSelected += HydrateView;
            View.PersonSaved += PersistPerson;
            View.PersonAdded += SaveANewPerson;
        }
        private void HydrateView(object sender, EventArgs e)
        {
            var selectedPerson = repository.GetById(View.SelectedPersonId);
            View.Name = selectedPerson.Name;
        }
        private void PersistPerson(object sender, EventArgs e)
        {
            var selectedPerson = repository.GetById(View.SelectedPersonId);
            selectedPerson.Name = View.Name;
            repository.Save(selectedPerson);
            HydrateAllPeople();
        }
        private void SaveANewPerson(object sender, EventArgs e)
        {
            var person = new Person {Name = View.Name};
            repository.Save(person);
            HydrateAllPeople();
        }


        
        
    }
}